package com.softer.wxzj.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softer.wxzj.common.entity.CommonResult;
import com.softer.wxzj.common.entity.Page;
import com.softer.wxzj.common.enums.NumStrEnum;
import com.softer.wxzj.common.enums.NumberEnum;
import com.softer.wxzj.common.enums.ShiroResultEnum;
import com.softer.wxzj.common.error.CourseException;
import com.softer.wxzj.common.util.NumGeneratorUtil;
import com.softer.wxzj.common.util.ShiroUserUtil;
import com.softer.wxzj.common.util.StringUtils;
import com.softer.wxzj.common.util.UUIDUtil;
import com.softer.wxzj.entity.AccCalculateInterestInfo;
import com.softer.wxzj.entity.AccInterestConfig;
import com.softer.wxzj.mapper.*;
import com.softer.wxzj.service.AccInterestConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zcz
 * @date 2019/7/5
 */
@Slf4j
@Service
public class AccInterestConfigServiceImpl implements AccInterestConfigService {
    @Autowired
    private AccInterestConfigMapper accInterestConfigMapper;
    @Autowired
    private AccCalculateInterestInfoMapper accCalculateInterestInfoMapper;
    @Autowired
    private AccCalculateInterestDetailLogMapper accCalculateInterestDetailLogMapper;
    @Autowired
    private AccCalculateInterestDetailMapper accCalculateInterestDetailMapper;
    @Autowired
    private BaseContractorBankInfoMapper baseContractorBankInfoMapper;

    @Override
    @Transactional
    public CommonResult insert(AccInterestConfig accInterestConfig) {
        int count = accInterestConfigMapper.getCountByInterestDate(accInterestConfig.getInterestDate());
        if (count > NumberEnum.ZERO.getNum()) {
            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "结息日期已存在，请重新选择");
        }
        accInterestConfig.setCreater(ShiroUserUtil.getUserName());
        accInterestConfig.setId(UUIDUtil.getUUID());
        int i = accInterestConfigMapper.insert(accInterestConfig);
        if (i==0){
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "未成功插入数据，请联系管理员");
        }
        //执行操作
        forSave();
        return CommonResult.ResponseResult(i);
    }

    /**
     * 生成结息表中的年份
     *
     * @param cofigDate
     * @param lastCalculationDate
     * @return
     */
//    private String getYear(String cofigDate, Date lastCalculationDate) {
//        SimpleDateFormat f = new SimpleDateFormat("yyyy");
//        String interestYear = f.format(lastCalculationDate);
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//        Date interestDate;
//        try {
//            //修改日期
//            interestDate = format.parse(interestYear + "-" + cofigDate);
//            //2019-01-01    2019-11-12
//            if (interestDate.before(lastCalculationDate)) {
//                interestYear = String.valueOf(Integer.parseInt(interestYear) + 1);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return interestYear;
//    }

    /**
     * 赋值AccCalculateInterestInfo
     *
     * @param accInterestConfig
     * @return
     */
    public AccCalculateInterestInfo setAccCalculateInterestInfo(AccInterestConfig accInterestConfig, String interestYear) {
        AccCalculateInterestInfo accCalculateInterestInfo = new AccCalculateInterestInfo();
        accCalculateInterestInfo.setId(UUIDUtil.getUUID());
        accCalculateInterestInfo.setInterestYear(interestYear);
        accCalculateInterestInfo.setAccountType(accInterestConfig.getAccountType());
        accCalculateInterestInfo.setInterestDate(accInterestConfig.getInterestDate());
        accCalculateInterestInfo.setInterestType(accInterestConfig.getInterestType());
        accCalculateInterestInfo.setCreater(ShiroUserUtil.getUserName());
        accCalculateInterestInfo.setState(NumStrEnum.ONE.getNum());
        accCalculateInterestInfo.setAccState(NumStrEnum.ZERO.getNum());
        accCalculateInterestInfo.setRateNo(NumGeneratorUtil.getLongNo(NumStrEnum.ONE.getNum()));
        return accCalculateInterestInfo;
    }

    @Override
    public CommonResult update(AccInterestConfig accInterestConfig) {
        String date = "";
        int count = accInterestConfigMapper.getCountByInterestDateAndId(accInterestConfig.getInterestDate(), accInterestConfig.getId());
        if (count > NumberEnum.ZERO.getNum()) {
            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "结息日期已存在，请重新选择");
        }
        accInterestConfig.setModifier(ShiroUserUtil.getUserName());
        //查询修改前
        AccInterestConfig info = accInterestConfigMapper.getInfo(accInterestConfig.getId());
        //查询之前的日期(结息表未结息数据)
        AccCalculateInterestInfo accCalculateInterestInfo = accCalculateInterestInfoMapper.selectByDate();
        //查询是否结息中  结息中不允许修改
        AccCalculateInterestInfo currentInfo = accCalculateInterestInfoMapper.getCurrentInfoByInterestDate(info.getInterestDate());
        if (null != currentInfo) {
            if (NumStrEnum.ONE.getNum().equals(currentInfo.getIsCalculation())) {
                return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "正在结息中，无法修改结息信息！");
            } else {
                //清空上次结息
                accCalculateInterestDetailLogMapper.deleteByRateNo(currentInfo.getRateNo());
                accCalculateInterestDetailMapper.deleteByRateNo(currentInfo.getRateNo());
                //删除当前结息
                // accCalculateInterestInfoMapper.delete(currentInfo.getId());
            }
        }
        //修改结息配置表
        int i = accInterestConfigMapper.updateSelective(accInterestConfig);
        AccCalculateInterestInfo a = new AccCalculateInterestInfo();
        //查询记账日期的数据
        AccCalculateInterestInfo acc = accCalculateInterestInfoMapper.selectMaxChange();
        //查询比记账日期大的值的第一个值
        AccInterestConfig oldAcc = new AccInterestConfig();
        ///如不等于空
        if (null != acc) {
            //查询里记账日期最近得值
            oldAcc = accInterestConfigMapper.selectMaxByDate(acc.getInterestDate());
            //若有则为这个值
            if (null != oldAcc) {
                a = setAccCalculateInterestInfo(oldAcc, acc.getInterestYear());
                accCalculateInterestInfoMapper.insert(a);
                date = a.getInterestYear() + "-" + a.getInterestDate();
            } else {//若没有则为结息配置最小值加一年
                AccInterestConfig accInterestConfig1 = accInterestConfigMapper.selectMinAll();
                a = setAccCalculateInterestInfo(accInterestConfig1, (Integer.parseInt(acc.getInterestYear()) + 1) + "");
                accCalculateInterestInfoMapper.insert(a);
                date = a.getInterestYear() + "-" + a.getInterestDate();
            }//若未结过息
        } else {
            //如果没有记账的数据则直接添加最小值并且大于银行使用日期的数据
            String base = baseContractorBankInfoMapper.getMinTime();
            if (StringUtils.isBlank(base)) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "请先维护承办银行信息");
            }
            oldAcc = accInterestConfigMapper.selectMaxByDate(base.substring(5));
            if (null != oldAcc) {//如果有的话则添加数据
                a = setAccCalculateInterestInfo(oldAcc, (base.substring(0, 4)));
                accCalculateInterestInfoMapper.insert(a);
                date = a.getInterestYear() + "-" + a.getInterestDate();
            } else {//若没有则删除之前的数据
                accCalculateInterestInfoMapper.deleteMin(accCalculateInterestInfo.getId());
                return CommonResult.ResponseResult(i);
            }
        }
        //新添加进去的值的日期
        LocalDate newDateTime = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        //查询之前的日期
        LocalDate beginDateTime;
        if (null != accCalculateInterestInfo) {
            beginDateTime = LocalDate.parse(accCalculateInterestInfo.getInterestYear() + "-" + accCalculateInterestInfo.getInterestDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            if (accCalculateInterestInfoMapper.selectNotHaveAcc() > 1) {
                //若 新在后 旧在前
                if (newDateTime.isBefore(beginDateTime)) {
                    accCalculateInterestInfoMapper.deleteMin(accCalculateInterestInfo.getId());
                } else if (newDateTime.compareTo(beginDateTime) == 0) {
                    accCalculateInterestInfoMapper.deleteMin(accCalculateInterestInfo.getId());
                } else {
                    AccInterestConfig accHave = accInterestConfigMapper.selectByDate(accCalculateInterestInfo.getInterestDate());
                    if (null == accHave) {
                        accCalculateInterestInfoMapper.deleteMin(accCalculateInterestInfo.getId());
                    } else {
                        accCalculateInterestInfoMapper.deleteMin(a.getId());
                    }
                }
            }
        }
        if (null != currentInfo && NumStrEnum.ONE.getNum().equals(currentInfo.getIsCalculation())) {
            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "正在结息中，无法修改结息信息！");
        }
        if (NumberEnum.ZERO.getNum() == i) {
            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum());
        }
        return CommonResult.ResponseResult(i);
    }


    /**
     * 遍历配置表   执行对应操作
     */
    protected void forSave() {
        String base = baseContractorBankInfoMapper.getMinTime();
        if (StringUtils.isBlank(base)) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "请先维护承办银行信息");
        }
        LocalDate beginDateTime = LocalDate.parse(base, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        AccCalculateInterestInfo currentInfo = accCalculateInterestInfoMapper.getCurrentInfo();
        Map<String, Date> map = getDateMap(currentInfo);
        //未结息日期
        Date currentInfoDate = map.get("currentInfoDate");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String current = sdf.format(currentInfoDate);
        //未结息
        String date = current.substring(5);
        //已结息日期
        Date lastCalculationDate = map.get("lastCalculationDate");
        String endDateAll = sdf.format(map.get("lastCalculationDate"));
        String endDate = endDateAll.substring(5);
        //已结息的年
        Integer endYear = Integer.valueOf(endDateAll.substring(0, 4));
        //未结息的年
        Integer year = Integer.valueOf(current.substring(0, 4));
        //如果结息的年与未结息的年不同
        String maxDate = "";
        if (!year .equals(endYear) &&  3000!=year) {
            maxDate = accInterestConfigMapper.selectMaxNextYear(endDate);
            if (StringUtils.isBlank(maxDate)) {
                String minDate = accInterestConfigMapper.selectMin(date);
                if (StringUtils.isBlank(minDate)) {
                    maxDate = endYear + 1 + "-" + accInterestConfigMapper.selectMinOne();
                } else {
                    maxDate = endYear + 1 + "-" + minDate;
                }
            } else {
                String dateMm=maxDate;
                maxDate = endYear + "-" + dateMm;
                LocalDate localDate = LocalDate.parse(maxDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
if (localDate.isBefore(beginDateTime)){
    String minDate = accInterestConfigMapper.selectMaxDate(dateMm);
    if (StringUtils.isBlank(minDate)){
        maxDate = endYear+1 + "-" + dateMm;
    }else {
        LocalDate minLocalDate= LocalDate.parse(endYear+"-"+minDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        if (minLocalDate.isAfter(beginDateTime)) {
            maxDate = endYear+ "-" + minLocalDate;
        }else {
            String macDate = accInterestConfigMapper.selectMaxDate(base.substring(5));
            if (StringUtils.isBlank(macDate)) {
                maxDate = endYear+ "-" + beginDateTime;
            }else {
                maxDate = endYear+ "-" + macDate;
            }
        }
    }
}
            }
        } else {
            if (3000==year) {
                year = endYear;
                date = "12-31";
            }
            //查询有没有比他大的则为这个值，找出最小值+1
            maxDate = accInterestConfigMapper.selectMax(date, endDate);
            if (StringUtils.isBlank(maxDate)) {
                String minDate = accInterestConfigMapper.selectMin(date);
                if (StringUtils.isBlank(minDate)) {
                    maxDate = year + 1 + "-" + accInterestConfigMapper.selectMinOne();
                } else {
                    maxDate = year + 1 + "-" + minDate;
                }
            } else {
                maxDate = year + "-" + maxDate;
                LocalDate localDate = LocalDate.parse(maxDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
             //若配置日期小于承办银行的日期
                if (localDate.isBefore(beginDateTime)) {
                    String minDate = accInterestConfigMapper.selectMaxDate(base.substring(5));
                    if (null != minDate) {
                        LocalDate minLocalDate = LocalDate.parse(endYear + "-" + minDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                        if (minLocalDate.isAfter(beginDateTime)) {
                            maxDate = endYear + "-" + minDate;
                        } else {
                            maxDate = base;
                        }
                    }else {
                        maxDate = base;
                    }
                }
            }
        }
        Date interestDate = new Date();
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        //看是不是结息的最后一条数据
        if (!maxDate.substring(5).equals("null")) {
            try {
                interestDate = format1.parse(maxDate);
            } catch (ParseException e) {
                log.error("错误信息:()", e.getMessage(), e);
            }
            if (interestDate.after(lastCalculationDate)) {
                //若现在存的结息日期与之前的日期相同则修改为现在的日期
                if ( LocalDate.parse(current, DateTimeFormatter.ofPattern("yyyy-MM-dd")).compareTo(beginDateTime)==0){
                    if (null != currentInfo) {
                        //清空上次结息
                        accCalculateInterestDetailLogMapper.deleteByRateNo(currentInfo.getRateNo());
                        accCalculateInterestDetailMapper.deleteByRateNo(currentInfo.getRateNo());
                        //删除当前结息
                        accCalculateInterestInfoMapper.delete(currentInfo.getId());
                    }
                    AccInterestConfig accInterestConfig = accInterestConfigMapper.selectByDate(maxDate.substring(5));
                    if (null==accInterestConfig){
                        accInterestConfig= accInterestConfigMapper.selectMinAllConfig();
                        accInterestConfig.setInterestDate(base.substring(5));
                        accInterestConfigMapper.selectByDate(maxDate.substring(5));
                    }
                    AccCalculateInterestInfo accCalculateInterestInfo = setAccCalculateInterestInfo(accInterestConfig, maxDate.substring(0, 4));
                    accCalculateInterestInfoMapper.insert(accCalculateInterestInfo);
                }else if (interestDate.before(currentInfoDate)) {
                    AccInterestConfig accInterestConfig = accInterestConfigMapper.selectByDate(maxDate.substring(5));
                 //若是空則表示为承办银行  他的结息类型根据第一个类型
                   if (null==accInterestConfig){
                       accInterestConfig= accInterestConfigMapper.selectMinAllConfig();
                       accInterestConfig.setInterestDate(base.substring(5));
                       accInterestConfigMapper.selectByDate(maxDate.substring(5));
                   }
                    AccCalculateInterestInfo accCalculateInterestInfo = setAccCalculateInterestInfo(accInterestConfig, maxDate.substring(0, 4));
                    if (null != currentInfo) {
                        //清空上次结息
                        accCalculateInterestDetailLogMapper.deleteByRateNo(currentInfo.getRateNo());
                        accCalculateInterestDetailMapper.deleteByRateNo(currentInfo.getRateNo());
                        //删除当前结息
                        accCalculateInterestInfoMapper.delete(currentInfo.getId());
                    }
                    //活期赋值利率类型为1活期（定期自选利率类型，设置利率、利息分配无利率类型）
                    if ("306".equals(accCalculateInterestInfo.getInterestType())) {
                        accCalculateInterestInfo.setRateType(NumStrEnum.ONE.getNum());
                    }
                    if (null == currentInfo) {

                        if (accCalculateInterestInfoMapper.selectHaveAcc() < 1) {
                            LocalDate nowTime = LocalDate.parse(accCalculateInterestInfo.getInterestYear() + "-" + accCalculateInterestInfo.getInterestDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                            if (beginDateTime.isBefore(nowTime)) {
                                accCalculateInterestInfoMapper.insert(accCalculateInterestInfo);
                            }else{
                                accCalculateInterestInfo.setInterestDate(baseContractorBankInfoMapper.getMinTime().substring(5));
                                accCalculateInterestInfoMapper.insert(accCalculateInterestInfo);
                            }
                        } else {
                            accCalculateInterestInfoMapper.insert(accCalculateInterestInfo);
                        }
                    } else {
                        accCalculateInterestInfoMapper.insert(accCalculateInterestInfo);
                    }
                }
            }
        } else {
            //若是则查询他的未记账数据并删除
            if (null != currentInfo) {
                //清空上次结息
                accCalculateInterestDetailLogMapper.deleteByRateNo(currentInfo.getRateNo());
                accCalculateInterestDetailMapper.deleteByRateNo(currentInfo.getRateNo());
                //删除当前结息
                accCalculateInterestInfoMapper.delete(currentInfo.getId());
            }
        }
    }


    /**
     * 时间转换 获取最近结息日期  未结息日期  输入日期
     *
     * @return
     */
    private Map<String, Date> getDateMap(AccCalculateInterestInfo currentInfo) {
        Map<String, Date> map = new HashMap<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //最后结息日期
        String base = baseContractorBankInfoMapper.getMinTime();
        if (StringUtils.isBlank(base)) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "请先维护承办银行信息");
        }
        String newYear = base.substring(0, 4);
        AccCalculateInterestInfo lastCalculationInfo = accCalculateInterestInfoMapper.getLastCalculationInfo();
        //未结息日期
        Date currentInfoDate = null;
        //已结息日期
        Date lastCalculationDate = null;
        try {
            //添加未使用
            currentInfoDate = null == currentInfo || null == currentInfo.getInterestDate() ? format.parse("3000-01-01") : format.parse(currentInfo.getInterestYear() + "-" + currentInfo.getInterestDate());
            //结息

            lastCalculationDate = null == lastCalculationInfo || null == lastCalculationInfo.getInterestDate() ? format.parse(newYear + "-01-01") : format.parse(lastCalculationInfo.getInterestYear() + "-" + lastCalculationInfo.getInterestDate());
        } catch (Exception e) {
            log.error("错误信息:()", e.getMessage(), e);
        }
        map.put("currentInfoDate", currentInfoDate);
        map.put("lastCalculationDate", lastCalculationDate);
        return map;
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult delete(String id) {
        //删除结息表
        AccInterestConfig accInterestConfig = accInterestConfigMapper.getInfo(id);
        //查询是否结息中  结息中不允许删除
        AccCalculateInterestInfo currentInfo = accCalculateInterestInfoMapper.getCurrentInfoByInterestDate(accInterestConfig.getInterestDate());
        if (null != currentInfo && NumStrEnum.ONE.getNum().equals(currentInfo.getIsCalculation())) {
            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "正在结息中，无法删除结息信息！");
        }
        //删除配置表
        int i = accInterestConfigMapper.delete(id);
        //根据结息类型和结息日期删除状态为当前状态的结息记录
        accCalculateInterestInfoMapper.deleteByInterestTypeAndInterestDate(accInterestConfig.getInterestType(), String.valueOf(accInterestConfig.getInterestDate()));
        forSave();
        return CommonResult.ResponseResult(i);
    }

    @Override
    public PageInfo<AccInterestConfig> getList(Page page, AccInterestConfig accInterestConfig) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<AccInterestConfig> list = accInterestConfigMapper.getList(accInterestConfig);
        PageInfo<AccInterestConfig> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public AccInterestConfig getInfo(String id) {
        return accInterestConfigMapper.getInfo(id);
    }

}
